import React, { useState } from 'react';
  import { motion, AnimatePresence } from 'framer-motion';
  import { ExpenseCategory, CATEGORY_CONFIG } from '../types';
  import { useExpenses } from '../contexts/ExpenseContext';
  import ExpenseList from '../components/ExpenseList';
  import AddExpense from '../components/AddExpense';
  import Statistics from '../components/Statistics';
  import { useTheme } from '../hooks/useTheme';
  import ShareModal from '../components/ShareModal';

export default function Home() {
  const { expenses, addExpense, deleteExpense } = useExpenses();
  const { theme, toggleTheme } = useTheme();
  const [showAddForm, setShowAddForm] = useState<boolean>(false);
  const [showShareModal, setShowShareModal] = useState<boolean>(false);
  const [activeTab, setActiveTab] = useState<'list' | 'statistics' | 'monthly'>('list');
  const [selectedMonth, setSelectedMonth] = useState<string>(() => {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
  });
  
  // 优化handleAddExpense函数，确保正确添加记录
  const handleAddExpense = (expenseData: {
    amount: number;
    category: ExpenseCategory;
    description: string;
    date: string;
  }) => {
    try {
      // 确保amount是有效的数字
      const validAmount = typeof expenseData.amount === 'number' ? expenseData.amount : parseFloat(expenseData.amount as any) || 0;
      
      // 创建有效的消费记录对象
      const validExpense = {
        amount: validAmount,
        category: expenseData.category,
        description: expenseData.description.trim(),
        date: expenseData.date
      };
      
      // 调用addExpense函数添加记录
      addExpense(validExpense);
      
      // 关闭表单
      setShowAddForm(false);
      
    } catch (error) {
      console.error('Failed to add expense:', error);
    }
  };
  
  return (
    <div className={`min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 transition-colors duration-300`}>
       {/* 头部 */}
      <header className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-100 dark:border-gray-700 sticky top-0 z-10">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold">支出记录</h1>
            <div className="flex space-x-2">
              <button
                onClick={() => setShowShareModal(true)}
                className="p-2 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                aria-label="分享应用"
              >
                <i className="fas fa-share-alt"></i>
              </button>
              <button
                onClick={toggleTheme}
                className="p-2 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                aria-label={theme === 'light' ? '切换到深色模式' : '切换到浅色模式'}
              >
                {theme === 'light' ? (
                  <i className="fas fa-moon"></i>
                ) : (
                  <i className="fas fa-sun"></i>
                )}
              </button>
            </div>
          </div>
          
          {/* 标签页 */}
          <div className="flex mt-4 border-b border-gray-200 dark:border-gray-700 overflow-x-auto no-scrollbar">
            <button
              className={`py-2 px-4 font-medium text-sm border-b-2 transition-colors whitespace-nowrap ${
                activeTab === 'list'
                  ? 'border-blue-500 text-blue-500'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
              onClick={() => setActiveTab('list')}
            >
              消费列表
            </button>
            <button
              className={`py-2 px-4 font-medium text-sm border-b-2 transition-colors whitespace-nowrap ${
                activeTab === 'statistics'
                  ? 'border-blue-500 text-blue-500'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
              onClick={() => setActiveTab('statistics')}
            >
              消费统计
            </button>
            <button
              className={`py-2 px-4 font-medium text-sm border-b-2 transition-colors whitespace-nowrap ${
                activeTab === 'monthly'
                  ? 'border-blue-500 text-blue-500'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
              onClick={() => setActiveTab('monthly')}
            >
              按月统计
            </button>
          </div>
        </div>
      </header>
      
      {/* 主内容区 */}
      <main className="container mx-auto px-4 py-6">
        {activeTab === 'list' && (
          <>
            <div className="mb-6">
              <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-md border border-gray-100 dark:border-gray-700">
                <h2 className="text-xl font-bold mb-1">本月支出</h2>
                <div className="text-3xl font-bold text-blue-500">
                  ¥{expenses
                    .filter(expense => {
                      const expenseDate = new Date(expense.date);
                      const currentDate = new Date();
                      return expenseDate.getMonth() === currentDate.getMonth() && 
                             expenseDate.getFullYear() === currentDate.getFullYear();
                    })
                    .reduce((total, expense) => total + expense.amount, 0)
                    .toFixed(2)}
                </div>
              </div>
            </div>
            
            <ExpenseList expenses={expenses} onDelete={deleteExpense} />
          </>
        )}
        
        {activeTab === 'statistics' && (
          <Statistics expenses={expenses} />
        )}
        
        {activeTab === 'monthly' && (
          <div className="space-y-6">
            {/* 月份选择器 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-md border border-gray-100 dark:border-gray-700">
              <h2 className="text-lg font-bold mb-4">选择月份</h2>
              <div className="flex items-center space-x-4">
                <input
                  type="month"
                  value={selectedMonth}
                  onChange={(e) => setSelectedMonth(e.target.value)}
                  className="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                />
              </div>
            </div>
            
            {/* 月度统计数据 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-md border border-gray-100 dark:border-gray-700">
              <h2 className="text-xl font-bold mb-4">
                {selectedMonth ? `${selectedMonth.substring(0, 4)}年${selectedMonth.substring(5)}月消费统计` : '选择月份查看统计'}
              </h2>
              
              {selectedMonth && (
                <>
                  {/* 月度总支出 */}
                  <div className="mb-6">
                    <h3 className="text-lg font-medium text-gray-700 dark:text-gray-300 mb-2">本月总支出</h3>
                    <div className="text-3xl font-bold text-blue-500">
                      ¥{expenses
                        .filter(expense => expense.date.startsWith(selectedMonth))
                        .reduce((total, expense) => total + expense.amount, 0)
                        .toFixed(2)}
                    </div>
                  </div>
                  
                  {/* 月度类别统计 */}
                  <div>
                    <h3 className="text-lg font-medium text-gray-700 dark:text-gray-300 mb-3">类别明细</h3>
                    <div className="space-y-3">
                      {Object.entries(
                        expenses
                          .filter(expense => expense.date.startsWith(selectedMonth))
                          .reduce((acc, expense) => {
                            acc[expense.category] = (acc[expense.category] || 0) + expense.amount;
                            return acc;
                          }, {} as Record<string, number>)
                      )
                        .sort(([, a], [, b]) => b - a)
                        .map(([category, amount]) => {
                          const categoryConfig = CATEGORY_CONFIG[category as keyof typeof CATEGORY_CONFIG];
                          const total = expenses
                            .filter(expense => expense.date.startsWith(selectedMonth))
                            .reduce((sum, expense) => sum + expense.amount, 0);
                          const percentage = total > 0 ? (amount / total) * 100 : 0;
                          
                          return (
                            <div key={category} className="flex items-center justify-between">
                              <div className="flex items-center">
                                <div className={`p-2 rounded-full ${categoryConfig.color} mr-3`}>
                                  <i className={`${categoryConfig.icon} text-white text-sm`}></i>
                                </div>
                                <div>
                                  <p className="font-medium">{categoryConfig.name}</p>
                                  <p className="text-sm text-gray-500 dark:text-gray-400">{percentage.toFixed(1)}%</p>
                                </div>
                              </div>
                              <div className="text-right">
                                <p className="font-bold">¥{amount.toFixed(2)}</p>
                              </div>
                            </div>
                          );
                        })}
                    </div>
                  </div>
                </>
              )}
              
              {selectedMonth && expenses.filter(expense => expense.date.startsWith(selectedMonth)).length === 0 && (
                <div className="flex flex-col items-center justify-center py-10 text-center">
                  <div className="bg-gray-100 dark:bg-gray-700 p-3 rounded-full mb-3">
                    <i className="fas fa-calendar-alt text-gray-400"></i>
                  </div>
                  <p className="text-gray-500 dark:text-gray-400">
                    {selectedMonth.substring(0, 4)}年{selectedMonth.substring(5)}月暂无消费记录
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </main>
      
      {/* 添加按钮 */}
      <motion.button
        className="fixed right-6 bottom-6 p-4 rounded-full bg-blue-500 text-white shadow-lg z-20"
        whileHover={{ scale: 1.1 }}
        whileTap={{ scale: 0.9 }}
        onClick={() => setShowAddForm(true)}
        aria-label="添加记录"
      >
        <i className="fas fa-plus text-xl"></i>
      </motion.button>
      
       {/* 添加记录弹窗 */}
      <AnimatePresence>
        {showAddForm && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black bg-opacity-50 z-30"
              onClick={() => setShowAddForm(false)}
            />
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 20 }}
              transition={{ duration: 0.3 }}
              className="fixed bottom-0 left-0 right-0 z-40 max-h-[90vh] overflow-y-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="container mx-auto p-4">
                <AddExpense onAdd={handleAddExpense} onClose={() => setShowAddForm(false)} />
                <div className="mt-4 text-sm text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 p-3 rounded-lg">
                    <p className="mb-2"><i className="fas fa-mobile-alt mr-2"></i> 手机使用指南：</p>
                   <ul className="list-disc list-inside text-xs space-y-1">
                     <li>直接通过手机浏览器访问应用网址（需要先部署）</li>
                     <li><span className="font-medium">添加到主屏幕方法：</span></li>
                     <li className="ml-4">- 苹果iOS：点击底部"分享"按钮 → 选择"添加到主屏幕"</li>
                     <li className="ml-4">- 安卓设备：点击顶部"菜单"按钮 → 选择"添加到主屏幕"</li>
                     <li>添加后，应用将像原生APP一样出现在您的主屏幕上</li>
                     <li>所有数据安全保存在您的设备本地，不会丢失</li>
                   </ul>
                </div>
                 <div className="mt-4 text-sm text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 p-3 rounded-lg">
                  💡 提示：您的消费记录安全地保存在浏览器的本地存储中，即使关闭应用再重新打开，数据也不会丢失。如需多人使用，建议将应用部署到网络上，通过链接分享给朋友。
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
      
      {/* 分享弹窗 */}
      <AnimatePresence>
        {showShareModal && (
          <ShareModal onClose={() => setShowShareModal(false)} />
        )}
      </AnimatePresence>
    </div>
  );
}